﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace AgentSystem.AgentCreator.Util
{
    /// <summary>
    /// Json Helper to serialize and deserialize in/from JSON format.
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// Jsons the serialize.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputObject">The input object.</param>
        /// <returns>JSON string</returns>
        public static string JsonSerialize<T>(T inputObject)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string jsonString = string.Empty;

            using (MemoryStream memStream = new MemoryStream())
            {
                serializer.WriteObject(memStream, inputObject);
                jsonString = Encoding.UTF8.GetString(memStream.ToArray());
            }

            return jsonString;
        }


        /// <summary>
        /// Jsons the deserialize.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString">The json string.</param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string jsonString)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T outputObject;

            using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                outputObject = (T)serializer.ReadObject(memStream);
            }

            return outputObject;
        }
    }
}
